package com.zqh.apiindeximgquery.service.impl;

import com.alibaba.fastjson.JSON;
import com.zqh.apiindeximgquery.redis.RedisUtil;
import com.zqh.apiindeximgquery.service.ApiIndexImgQueryService;
import com.zqh.myfmmall.clients.IndexImgQueryClient;
import com.zqh.myfmmall.constants.RedisExpireTime;
import com.zqh.myfmmall.result.Result;
import com.zqh.myfmmall.rowbeans.entity.IndexImg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

;import java.util.List;

/**
 * @Description :
 * @Author :kono淇杭哒、
 * @Create 2022-02-18 2:19
 */
@Service("apiIndexImgQueryService")
public class ApiIndexImgQueryServiceImpl implements ApiIndexImgQueryService{
    @Autowired
    private IndexImgQueryClient indexImgQueryClient;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Result current() {
        Result result = null;
        //对应数据的基础key
        String redisKey = "indeximg";
        List<IndexImg> indexImgs = (List<IndexImg>) redisUtil.get(redisKey);
        //一级缓存不为空
        if (indexImgs != null) {
            result = Result.success(indexImgs);
            //二级缓存配合redis分布式锁解决缓存击穿问题
        }else{
            List<IndexImg> indexImgsBackup = (List<IndexImg>) redisUtil.get(redisKey + "-backup");
            if (indexImgsBackup != null) {
                result = Result.success(indexImgsBackup);
                boolean locked = redisUtil.setnx(redisKey + "-lock","1");
                try {
                    if (locked){
                        Result queryResult = indexImgQueryClient.retrieveCurrent();
                        if (!queryResult.getSuccess()){
                            return Result.internalServerError();
                        }
                        updateForRedisWithBackUp(redisKey,queryResult.getData());
                    }
                } finally {
                    redisUtil.del(redisKey + "-lock");
                }
            }else {
                result = indexImgQueryClient.retrieveCurrent();
                if (!result.getSuccess()){
                    return Result.internalServerError();
                }
                updateForRedisWithBackUp(redisKey,result.getData());
            }
        }
        return result;
    }

    /**
     * 功能描述:
     * 设置某一数据的redis一级和二级缓存
     *
     * @param
     * @param key
     * @return void
     * @author kono曾淇杭哒！
     * @date 2022/3/16 20:54
     */
    public void updateForRedisWithBackUp(String key,Object value){
        //更新缓存
        redisUtil.set(key,value,
                RedisExpireTime.INDEXPICTURE.getTime(),RedisExpireTime.PRODUCT.getTimeUnit());
        redisUtil.set(key+"-backup",value,
                RedisExpireTime.INDEXPICTURE.getTime() + 30,RedisExpireTime.PRODUCT.getTimeUnit());
    }
}
